<template>
  <div class="detail-box">
    <div class="head">
      <p>{{ detail.name }}</p>
      <p>{{ detail.desc }}</p>
      <p>
        <span>{{ detail.price }}</span>
        <span>{{ detail.oldPrice }}</span>
      </p>
    </div>
    <div class="center">
      <good-info-item label="促销">12月好物放送，App领券购买直降120元</good-info-item>
      <good-info-item label="配送"
                      value-align="center">
        <span style="margin-right: 10px">至</span>
        <city-select/>
      </good-info-item>
      <good-info-item class="service"
                      label="服务">
        <span>无忧退货</span>
        <span>快速退款</span>
        <span>免费包邮</span>
        <router-link to="">了解详情</router-link>
      </good-info-item>
    </div>
    <div class="bottom">
      <good-info-item v-for="(spec, index1) in detail.specs"
                      label-margin-bottom="10px"
                      :key="spec.name"
                      :label="spec.name">
        <good-spec v-for="(specVal, index2) in spec.values"
                   :key="specVal.name"
                   :active="index2 === activeIndex[index1]"
                   :data="specVal"
                   @click="specClick(index1, index2)"/>
      </good-info-item>
      <good-info-item label="数量">
        <good-count v-model:count="count"/>
      </good-info-item>
      <div class="add-cart"
           @click="addCart">
        加入购物车
      </div>
    </div>
  </div>
</template>

<script lang="ts"
        setup>
import CitySelect from '@/components/library/CitySelect.vue'
import GoodCount from '@/components/library/GoodCount.vue'
import GoodInfoItem from '@/components/library/GoodInfoItem.vue'
import GoodSpec from '@/components/library/GoodSpec.vue'
import message from '@/components/library/Message/index'
import {useCartStore} from '@/stores/cart'
import type {GoodDetail, Skus, Spec, SpecValue} from '@/types/good'
import type {Ref} from 'vue'
import {computed, inject, ref, toRefs, watch} from 'vue'

let props = defineProps<{
  data: GoodDetail
}>()
let {data: detail} = toRefs(props)

let cartStore = useCartStore()

let activeIndex = ref<number[]>([])
// ['颜色@木耳边领-姜黄']
let activeObj = computed(() => {
  let res: string[] = []
  for (let index in activeIndex.value) {
    if (activeIndex.value[index] === -1) continue
    let spec: Spec | undefined = detail.value?.specs?.[index]
    let specValue: SpecValue | undefined = spec?.values?.[activeIndex.value[index]]
    res.push((spec?.name ?? '') + '@' + (specValue?.name ?? ''))
  }
  return res
})
let activeSku = ref<Skus>()
let activeSkuText = computed<string>((): string => {
  let res: string[] = []
  activeSku.value?.specs?.forEach(
    item => res.push(`${item.name}: ${item.valueName}`)
  )
  return res.join(' ')
})
// specs变化时设置activeIndex
watch(() => detail.value.specs, (newVal: Spec[] | undefined) => {
  activeIndex.value.length = newVal?.length ?? 0
  // 默认全设置为-1 代表未选中
  activeIndex.value.fill(-1)
}, {
  immediate: true
})

// spec切换点击事件
function specClick(index1: number, index2: number): void {
  // 点击已选中则取消选中，点击未选中则选中
  if (activeIndex.value[index1] === index2)
    activeIndex.value[index1] = -1
  else
    activeIndex.value[index1] = index2

  // 找到对应商品的sku
  activeSku.value = detail.value.skus?.find(item =>
    item.specs?.every(item => activeObj.value.includes(`${item.name}@${item.valueName}`))
  )
  // 如果sku存在，重置商品价格及库存
  if (activeSku.value) {
    detail.value.price = activeSku.value.price
    detail.value.oldPrice = activeSku.value.oldPrice
    detail.value.inventory = activeSku.value.inventory
  }
}

// 商品数量
let count = inject<Ref<number>>('count')

// 加入购物车按钮点击事件
async function addCart(): Promise<void> {
  if (!activeSku.value) return message.error('请选择完整规格')
  if (!count?.value) return message.error('数量不能为0')

  let res = await cartStore.addInCart({
    attrsText: activeSkuText.value,
    id: detail.value.id,
    name: detail.value.name,
    nowPrice: activeSku.value.price,
    picture: detail.value.mainPictures?.[0],
    price: activeSku.value?.price,
    skuId: activeSku.value?.id,
    stock: activeSku.value?.inventory,
    count: count?.value,
    selected: true,
    isEffective: true
  })
  if (!res) return message.error('加入购物车失败')
  message.success('加入购物车成功')
}
</script>

<style lang="less"
       scoped>
.detail-box {
  padding: 30px 0;
  width: 660px;
  min-height: 600px;

  .head {
    p:nth-of-type(1) {
      font-size: 22px;
    }

    p:nth-of-type(2) {
      margin-top: 10px;
      color: #999999;
    }

    p:nth-of-type(3) {
      margin-top: 10px;

      span {
        &:before {
          content: "￥";
          display: inline-block;
          font-size: 16px;
          width: 13px;
        }

        &:nth-of-type(1) {
          color: @priceColor;
          padding-right: 10px;
          font-size: 22px;
        }

        &:nth-of-type(2) {
          color: #999999;
          font-size: 16px;
          text-decoration: line-through;
        }
      }
    }
  }

  .center {
    width: 500px;
    background-color: #f5f5f5;
    margin-top: 10px;
    padding: 20px 10px 0 10px;

    > * {
      padding-bottom: 20px;
    }

    .service {
      display: flex;

      span {
        margin-right: 10px;
        color: #666666;

        &:before {
          content: "•";
          color: @xtxColor;
          margin-right: 2px;
        }
      }

      a {
        color: @xtxColor;
      }
    }
  }

  .bottom {
    padding: 20px 10px 0 10px;
    width: 500px;

    .add-cart {
      display: flex;
      align-items: center;
      justify-content: center;
      width: 180px;
      height: 50px;
      margin-top: 20px;
      background-color: @xtxColor;
      border-radius: 4px;
      font-size: 16px;
      color: #ffffff;
      cursor: pointer;
    }
  }
}
</style>